package vn.nt.healthcare.server.ws.service.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import vn.nt.healthcare.server.ws.domain.Company;
import vn.nt.healthcare.server.ws.model.Subjects;
import vn.nt.healthcare.server.ws.repositories.CompanyRepository;
import vn.nt.healthcare.server.ws.service.SubjectsService;

@Service("subjectsService")
@Transactional
public class SubjectsServiceImpl implements SubjectsService {

	@Autowired
	private CompanyRepository companyRepository;

	@Override
	public Subjects findSubjectById(String company, int subjectId) {
		// TODO Auto-generated method stub
		Company company_ = companyRepository.findByCode(company);
		if (company_ == null) {
			return null;
		} else {
			Session session = null;
			try {
				session = ServiceHelper.openSession(company_);
				Subjects sub = (Subjects) session
						.get(Subjects.class, subjectId);
				return sub;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				ServiceHelper.closeSession(session);
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Subjects> findAllSubjects(String company) {
		// TODO Auto-generated method stub
		Company company_ = companyRepository.findByCode(company);
		if(company_ == null) {
			return null;
		} else {
			Session session = null;
			try {
				session = ServiceHelper.openSession(company_);
				StringBuilder sql = new StringBuilder(
						"SELECT DISTINCT sub FROM Subjects sub WHERE 1 = 1 ");
				Query query = session.createQuery(sql.toString());
				return query.list();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				ServiceHelper.closeSession(session);
			}
		}
		return null;
	}

}
